package com.video.controller.system;

import com.qf.entity.Page;
import com.qf.entity.ResultData;
import com.video.commons.loginaop.LoginContact;
import com.video.commons.loginaop.LoginUser;
import com.video.commons.loginaop.MustLogin;
import com.video.commons.page.PageHelper;
import com.video.commons.sendaop.SocketSend;
import com.video.commons.systemlog.LogType;
import com.video.commons.systemlog.SysLog;
import com.video.entity.ClientGroup;
import com.video.entity.ClientMsg;
import com.video.entity.TreeNode;
import com.video.entity.Webcon;
import com.video.netty.commons.utils.ChannelUtil;
import com.video.netty.send.*;
import com.video.service.client.IClientGroupService;
import com.video.service.client.IClientService;
import com.video.service.webcon.IWebconService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 终端控制层
 *
 * @Author ken
 * @Time 2018/12/15 14:36
 * @Version 1.0
 */
@Controller
@RequestMapping("/client")
public class ClientController {


    @Autowired
    private IClientService clientService;

    @Autowired
    private IClientGroupService groupService;

    @Autowired
    private ChannelUtil channelUtil;

    @Autowired
    private IWebconService webconService;


    //--------------------------------------------群组相关请求---------------------------------------------------
    /**
     * 群组管理
     * @return
     */
    @RequestMapping("/group")
    @ResponseBody
    public ResultData<List<TreeNode>> groupManager(){
        //获得所有组已经组内的终端
        List<TreeNode> treeNodes = groupService.queryAllGroup();
        return new ResultData<List<TreeNode>>().setData(treeNodes);
    }


    /**
     * 群组管理 - 根据当前分控查询分控所属的所有终端分组
     * @return
     */
    @RequestMapping("/groupWebcon")
    @ResponseBody
    @MustLogin
    public ResultData<Set<TreeNode>> groupManagerWebcon(@LoginUser Webcon webcon){

        //从数据库中查询，获得最新的登录信息
        webcon = webconService.getById(webcon.getAccount());
        String clients = webcon.getClients();

        Set<TreeNode> showTreeNodes = new HashSet<>();
        if(clients != null){
            //获得所有组以及组内的终端
            List<TreeNode> treeNodes = groupService.queryAllGroup();

            //循环所有分组和终端
            for (TreeNode treeNode : treeNodes) {
                //1-1|1-2
                //按照竖杠分割，获得当前分控所属的所有终端
                String[] arrays = clients.split("\\|");
                for (String array : arrays) {
                    //继续分割获得分组和终端
                    String[] clientGroup = array.split("-");
                    Integer groupId = Integer.parseInt(clientGroup[0]);
                    Integer clientId = Integer.parseInt(clientGroup[1]);

                    if((treeNode.getId() != null && groupId == treeNode.getId().intValue())
                            || (treeNode.getId() == null && clientId == treeNode.getUserid().intValue() && groupId == treeNode.getPid().intValue())){
                        showTreeNodes.add(treeNode);
                    }
                }
            }
        }

        return new ResultData<Set<TreeNode>>().setData(showTreeNodes);
    }


    /**
     * 添加群组
     * @return
     */
    @SysLog(value = LogType.INSERT, info = "添加了群组")
    @RequestMapping("/addgroup")
    @SocketSend(sendClass = TerminalGroupSend.class)
    public String addGroup(ClientGroup clientGroup){
        groupService.insert(clientGroup);
        return "redirect:/topage/clientgroup";
    }

    /**
     * 删除群组
     * @param id
     * @return
     */
    @SysLog(value = LogType.DELETE, info = "删除群组")
    @RequestMapping("/deletegroup")
    @ResponseBody
    @SocketSend(sendClass = TerminalGroupSend.class)
    public ResultData<Boolean> deleteGroup(Integer id, Integer gid, boolean isClient){
        groupService.deleteGroupOrClient(id, gid, isClient);
        return new ResultData<Boolean>().setData(true);
    }

    /**
     * 移动群组和设备
     * @return
     */
    @SysLog(value = LogType.UPDATE, info = "移动群组和设备")
    @RequestMapping("/move")
    @ResponseBody
    @SocketSend(sendClass = TerminalGroupSend.class)
    public ResultData<Boolean> moveClientGroup(Integer[] ids, Integer pid,  Integer oldpid, boolean isClient, boolean isCopy){
        groupService.move(ids, pid, oldpid, isClient, isCopy);
        return new ResultData<Boolean>().setData(true);
    }

    //--------------------------------------------终端相关请求---------------------------------------------------
    /**
     * 终端列表
     * @param model
     * @param page
     * @return
     */
    @PageHelper
    @RequestMapping("/list")
    public String clientList(Model model, Page page){
        List<ClientMsg> clientMsgs = clientService.queryList();
        model.addAttribute("clientMsgList", clientMsgs);
        return "system/clientlist";
    }

    /**
     * 终端列表搜索
     * @param model
     * @param page
     * @return
     */
    @PageHelper
    @RequestMapping("/search")
    public String clientSearch(String keyword, Model model, Page page){
        List<ClientMsg> clientMsgs = clientService.searchList(keyword);
        model.addAttribute("clientMsgList", clientMsgs);
        model.addAttribute("keyword", keyword);
        return "system/clientlist";
    }

    /**
     * 修改终端名称
     * @return
     */
    @SysLog(value = LogType.UPDATE, info = "修改终端名称")
    @RequestMapping("/updatename")
    @ResponseBody
    @SocketSend(params = {"#userid", "#uname", "#result"}, sendClass = TerminalRenameSend.class)
    public ResultData<Integer> updateName(Integer userid, String uname){
        int result = clientService.updateName(userid, uname);
        return new ResultData<Integer>().setData(result);
    }

    /**
     * 根据id查询终端信息
     * @param userid
     * @return
     */
    @RequestMapping("/querybyid")
    @ResponseBody
    public ResultData<ClientMsg> queryClientInfoById(Integer userid){
        ClientMsg clientMsg = clientService.getById(userid);
        return new ResultData<ClientMsg>().setData(clientMsg);
    }

    /**
     * 修改权限
     * @param userid
     * @param limits
     * @return
     */
    @RequestMapping("/updatePower")
    @ResponseBody
    @SocketSend(params = {"#userid", "#limits"}, sendClass = TerminalLimitsSend.class)
    @MustLogin(LoginContact.BACK_USER)
    public ResultData<String> updatePower(Integer userid, Integer[] limits){
        clientService.updatePowers(userid, limits);
        return new ResultData<String>().setData("succ");
    }

    /**
     * 修改终端ip
     * @return
     */
    @RequestMapping("/updateip")
    @ResponseBody
    @SocketSend(sendClass = ModifyTerminalConnectionSend.class, params = {"#ip", "#userids"})
    public ResultData<String> updateIp(String ip, String[] userids){
        return new ResultData<String>().setData("succ");
    }

    /**
     * 修改终端host
     * @return
     */
    @RequestMapping("/sethost")
    @ResponseBody
    @SocketSend(params = {"#cid", "#uids"}, sendClass = TalkhostSend.class)
    public ResultData<Integer> updateHost(Integer cid, @RequestParam("uids[]") Integer[] uids){
        int result = clientService.updateHost(cid);
        return new ResultData<Integer>().setData(result);
    }

    /**
     * 获得终端的host
     * @return
     */
    @RequestMapping("/getHost")
    @ResponseBody
    public ResultData<ClientMsg> queryHostClient(){
        ClientMsg clientMsg = clientService.getHost();
        return new ResultData<ClientMsg>().setData(clientMsg);
    }

    /**
     * 删除终端
     * @return
     */
    @RequestMapping("/deleteByUserid")
    @SocketSend(sendClass = DelTerminalSend.class, params = {"#userid"})
    @MustLogin(LoginContact.BACK_USER)
    public String deleteByUserid(Integer userid){
        clientService.deleteClientByUserId(userid);
        return "redirect:/client/list";
    }
}
